// 专用小模板
// 任何小仓库中:state,mutations,actions,getters
import { reqGetCode, reqRegister, reqUserLogin, reqUserLogout,reqUserInfo } from '@/api';

let state = {
     //验证码
     code: '',
     // 身份标识符  很重要【存储在vuex中】
     token: localStorage.getItem('TOKEN'),
     // 用户名字
     nickName: '',

};
let mutations = {
     GETCODE(state, code) {
          state.code = code;
     },
     SET_TOKEN(state, token) {
          state.token = token
     },
     SET_USERINFO(state, nickName) {
          state.nickName = nickName
     },
     CLEAR(state) {
          state.token = ""
          state.nickName = ""

          localStorage.removeItem('TOKEN')
     }
};
let actions = {
     //获取验证码
     async getCode({ commit, state, dispatch }, phone) {
          let result = await reqGetCode(phone);
          if (result.code == 200) {
               commit('GETCODE', result.data);
               return 'ok';
          } else {
               return Promise.reject();
          }
     },


     //    注册
     async register({ commit, state, dispatch }, obj) {
          let result = await reqRegister(obj);
          if (result.code == 200) {
               return 'ok';
          } else {
               return Promise.reject(new Error(result.message));
          }
     },

     // 登录
     async userLogin({ commit, state, dispatch }, data) {
          let result = await reqUserLogin(data)
          if (result.code == 200) {
               commit('SET_TOKEN', result.data.token)

               // 登录成功获取到token 需要持久化存储
               localStorage.setItem('TOKEN', result.data.token)

               return 'ok'
          } else {
               return Promise.reject(new Error(result.message));
          }

     },

     // 获取用户信息
     async getUserInfo({ commit, state, dispatch }) {
          let result = await reqUserInfo();
          if (result.code == 200) {
               commit('SET_USERINFO', result.data.nickName);
               return 'ok';
          } else {
               return Promise.reject();
          }
     },

     // 退出登录
     async logout({ commit, state, dispatch }) {
          let result = await reqUserLogout();
          if (result.code == 200) {
               commit('CLEAR');
               return 'ok';
          } else {
               return Promise.reject();
          }
     },



};
let getters = {};


// 对外暴露小仓库
export default {
     state,
     mutations,
     actions,
     getters,
}